import urllib3
import logging
import time
import json
import os
import redis
import pymysql
from selenium import webdriver
from selenium.webdriver.common.action_chains import ActionChains
from urllib import parse  

exceptionList=['48-7D-2E-19-A2-CA','98-EE-CB-05-CB-3F','6C-92-BF-4F-04-4C','10-78-D2-99-44-E5']
addlist=[]
dellist=[]
n=1

def tryFindElementById(id,time=10):
    while True:
        try:
            obj = browser.find_element_by_id(id)
        except:
            time=time-1
            if(time<=0):
                return False
            print("wait")
            time.sleep(1)
        else:
            return obj

def login():
    browser.get("http://192.168.2.250")
    time.sleep(2)
    inna=browser.find_element_by_id("login-username")
    logb=browser.find_element_by_id("login-btn")
    inpw=browser.find_element_by_css_selector(".text-text.password-text.password-hidden.l")
    inna.clear()
    inpw.clear()
    inna.send_keys("admin")
    inpw.send_keys("admin123")
    time.sleep(3)
    actions.move_to_element(logb)
    actions.click(logb)
    actions.perform()

def getWanIP():
    http=urllib3.PoolManager()
    url=browser.execute_script("return $.su.url('/admin/interface?form=status2')")
    print(url)
    r=http.request(
    'POST',
    'http://192.168.2.250'+url,
    headers={
        'Cookie':CookiesStr,
        #'X-Requested-With':'XMLHttpRequest',
        'Referer':'http://192.168.2.250/webpages/index.html',
        #'Host':'192.168.2.250',
        #'Accept':'application/json, text/javascript, */*; q=0.01',
        },
    fields={"data":"{'method':'get'}"}
    )
    d=r.data
    logging.debug(d.decode("utf-8"))
    return d.decode("utf-8")

def getCookiesStr():
    time.sleep(3)
    browser.get('http://192.168.2.250/cgi-bin/luci')
    time.sleep(1)
    CookiesStr=browser.execute_script("return document.cookie")
    logging.info(CookiesStr)
    browser.get('http://192.168.2.250/webpages/index.html')
    return CookiesStr

def tryExecuteJS(cmd):
    try:
        result=browser.execute_script("return "+cmd)
    except:
        logging.warning("execute JS error:"+cmd)
    else:
        return result

def getlists():
    addlist=[]
    dellist=[]
    rl=kvdb.get("maclist")
    cursor = conn.cursor()
    cursor.execute("select * from class_ip where a='1' and l!='1'")
    cl={}
    for v in cursor.fetchall():
        cl.update({v[2]:v[0]})
    conn.commit()
    cursor.close()
    lt={}
    if(rl==None):
        logging.warning("list error!")
        return False
    else:
        rl=json.loads(rl)
    for val in rl:
        lt.update({val['mac']:val['textname']})
        if(cl.get(val['mac'])==None):
            if(val['mac'] not in exceptionList):
                dellist.append(val['mac'])
    for val in cl:
        if(lt.get(val)==None):
            addlist.append(val)
    return (addlist,dellist)
    
def loadRouteMacList():
    result=tryExecuteJS("$.post($.su.url('/admin/mac_filter?form=mac_list'),{'data':JSON.stringify({'method':'get'})},function(msg){return msg},'json')")
    if(result['error_code'] == '0'):
        maclist=result['result']
        kvdb.set('maclist',json.dumps(maclist))
        return maclist
    else:
        logging.warning(result['error_code'])
        kvdb.set('error_code',result['error_code'])

def addmac(addlist):
    '''
    cl=kvdb.get("cmaclist")
    cl=json.loads(cl)
    '''
    cursor = conn.cursor()
    cursor.execute("select * from class_ip where a='1' and l!='1'")
    cl={}
    for v in cursor.fetchall():
        cl.update({v[2]:v[0]})
    conn.commit()
    cursor.close()
    for v in addlist:
        js="$.post($.su.url('/admin/mac_filter?form=mac_list'),{'data':JSON.stringify({'method':'add','params':{'index':1,'old':'add','new':{'textname':'%s','mac':'%s'},'key':'add'}})},function(msg){return msg},'json')"%(cl.get(v),v)
        tryExecuteJS(js)
        logging.info("ADDMAC:%s\t%s"%(cl.get(v),v))
        time.sleep(0.2)

def delmac(dellist):
    for v in dellist:
        maclist=loadRouteMacList()
        time.sleep(0.2)
        for i in maclist:
            if(i['mac']==v):
                js="$.post($.su.url('/admin/mac_filter?form=mac_list'),{'data':JSON.stringify({'method':'delete','params':{'key':'key-%d','index':'%d'}})},function(msg){return msg},'json')"%(maclist.index(i),maclist.index(i))
                tryExecuteJS(js)
                logging.info("DELMAC:%s\t%s"%(i["textname"],i['mac']))
                time.sleep(0.2)

browser = webdriver.Firefox()
browser.maximize_window()
browser.implicitly_wait(10)
actions = ActionChains(browser)
logging.basicConfig(level=logging.INFO,format='%(asctime)s -%(levelname)s -%(process)d -%(module)s -%(funcName)s -%(message)s')

kvdb = redis.Redis(host='localhost', port=6379,db=0,password='Af1121113')
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='demhghc', db='zthubo', charset='utf8')
cursor = conn.cursor()


login()
#CookiesStr=getCookiesStr()
#time.sleep(3)
#print(getWanIP())
#wanlist=browser.execute_script("return $.post($.su.url('/admin/interface?form=status2'),{'data':JSON.stringify({'method':'get'})},function(msg){return msg},'json')")
#print(wanlist,type(wanlist))
#kvdb.set('wanip',wanlist['result']['normal'][4]['ipaddr'])


#logging.info("IP:%s"%(wanlist["result"]["normal"][4]["ipaddr"]))
'''
#
$.post($.su.url('/admin/interface?form=status2'),{'data':JSON.stringify({"method":"get"})},function(msg){return msg},'json')

$.post($.su.url('/admin/mac_filter?form=mode'),{'data':JSON.stringify({"method":"get"})},function(msg){return msg},"json")

$.post($.su.url('/admin/mac_filter?form=mode'),{'data':JSON.stringify({"method":"set","params":{"enable":"on","filter_mode":"white","interfaces":"LAN"}})},function(msg){return msg},"json")

$.post($.su.url('/admin/mac_filter?form=mac_list'),{'data':JSON.stringify({"method":"add","params":{"index":6,"old":"add","new":{"textname":"bb","mac":"98-EE-CB-05-0B-4F"},"key":"add"}})},function(msg){return msg},"json")

$.post($.su.url('/admin/mac_filter?form=mac_list'),{'data':JSON.stringify({"method":"delete","params":{"key":"key-7","index":"7"}})},function(msg){return msg},"json")

$.post($.su.url('/admin/mac_filter?form=mac_list'),{'data':JSON.stringify({"method":"get"})},function(msg){return msg},"json")


'''

#打开mac过滤
tryExecuteJS("$.post($.su.url('/admin/mac_filter?form=mode'),{'data':JSON.stringify({'method':'set','params':{'enable':'on'}})},function(msg){return msg},'json')")
while True:
    
    with open(os.path.dirname(__file__)+"/com.txt","r+") as file:
        cmd=file.read()
    with open(os.path.dirname(__file__)+"/com.txt","w+") as file:
        file.write("")
    try:
        res=browser.execute_script("return "+cmd)
    except:
        print("js error!")
    else:
        if(cmd != ""):
            logging.info(cmd)
            print(type(res))
            print(res)
    loadRouteMacList()
    (addlist,dellist)=getlists()
    print(addlist)
    print(dellist)
    addmac(addlist)
    delmac(dellist)
    n=n+1
    print(n)
    time.sleep(15)
    if(n>100):
        n=0
        getCookiesStr()

conn.close()

